﻿using System.ServiceModel.Description;
using CoreEx.Common.Extensions;
using LinFu.IoC;
using LinFu.IoC.Configuration;

namespace CoreEx.ServiceModel.Implementation
{
    /// <summary>
    /// Initializes a <see cref="ServiceEndpoint"/> by adding all registered <see cref="IEndpointBehavior"/>
    /// implementations.
    /// </summary>
    [Implements(typeof(IInitializer<ServiceEndpoint>), ServiceName = "ServiceEndPointInitializer")]
    public class ServiceEndPointInitializer : InitializerBase<ServiceEndpoint>
    {
        /// <summary>
        /// Adds all registered <see cref="IEndpointBehavior"/> implementations to 
        /// the <see cref="ServiceEndpoint.Behaviors"/> collection.
        /// </summary>
        /// <param name="serviceEndpoint">The target service endpoint.</param>
        public override void Initialize(ServiceEndpoint serviceEndpoint)
        {                        
            var registeredEndpointBehaviors = ServiceContainer.GetServices<IEndpointBehavior>();
            registeredEndpointBehaviors.ForEach(eb => serviceEndpoint.Behaviors.Add(eb));

            serviceEndpoint.Contract.Operations.ForEach(InitializeOperation);
        }

        private void InitializeOperation(OperationDescription operationDescription)
        {
            var operationInitializers = ServiceContainer.GetServices<IInitializer<OperationDescription>>();
            operationInitializers.ForEach(oi => oi.Initialize(operationDescription));
        }
    }
}
